# Edge Impulse - OpenMV Object Detection Example
import sensor, time,tf,gc,math,lcd
from button import BUTTON
object_s=0
flag_lost=0
max_object=(0,0,0,0,0.0)

net = None
labels = None
confidence=0.7

try:
    # load the model, alloc the model file on the heap if we have at least 64K free after loading
    labels,net = tf.load_builtin_model('yoloface50k')
    #net = tf.load("yoloface.tflite",load_to_fb=True)
except Exception as e:
    raise Exception('Failed to load "yoloface", did you copy the .tflite and labels.txt file onto the mass-storage device? (' + str(e) + ')')

print(net)
def find_max_object(objects):
    max_size=0
    max_object=(0,0,0,0,0.0)
    for object in objects:
        if object[2]*object[3]> max_size:
            max_object=object
            max_size = object[2]*object[3]
    return max_object

def face_detect(img):
    rid=img.width()/img.height()
    objects=net.detect_yolo(img,confidence=0.75, anchors=[9,14,12,17,22,21],nms=0.2)#anchors=[9,14,12,17,22,21]#anchors=[21,28,34,49,61,77]
    #if (len(objects) == 0): continue # no detections for this class?
    if len(objects):
        for d in objects :
            #rect=(d.x(), d.y(), d.w(), d.h())
            rect=(int(d.x()/rid), d.y(), int(d.w()/rid), d.h())
            img.draw_rectangle(rect,color=(255,255,0)) #检测为白色框
            img.draw_string(d.x(), d.y()-10, "face %.3f"%(d.output()))
    return None

sensor.reset()                         # Reset and initialize the sensor.
sensor.set_pixformat(sensor.GRAYSCALE)    # Set pixel format to RGB565 (or GRAYSCALE)
sensor.set_framesize(sensor.V240X240)
#sensor.set_windowing(240,240)
sensor.skip_frames(time=1000) # Let new settings take affect.
#sensor.set_vflip(True)
#sensor.set_hmirror(True)
clock = time.clock()
#lcd.init(type=2,width=240,height=320)
lcd.init()
button=BUTTON()  #声明按键，梦飞openmv只有一个按键，因此直接内部指定了按键
click_timer=time.ticks_ms() #计时参数
while(True):
    clock.tick()
    img = sensor.snapshot()
    face_detect(img)
    print(clock.fps(), "fps", end="\n\n")
    lcd.display(img)
    gc.collect()
    if button.state():
        click_timer=time.ticks_ms()          #开始计时
        while button.state():  pass       #等待按键抬起
        if time.ticks_ms()-click_timer>2000: #按键时长超过2s
            sensor.dealloc_extra_fb()
            del net
            break                         #循环退出，回到主界面
    else :
        click_timer=time.ticks_ms()#计时更新

